package com.milk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milk.context.BaseContext;
import com.milk.entity.*;
import com.milk.exception.BaseException;
import com.milk.mapper.*;
import com.milk.properties.LotteryProperties;
import com.milk.service.LotteryService;
import com.milk.vo.UserLotteryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service

public class LotteryServiceImpl extends ServiceImpl<LotteryMapper, Lottery> implements LotteryService {

    @Autowired
    private LotteryMapper lotteryMapper;
    @Autowired
    private UserLotteryMapper userLotteryMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private UserMilkteaMapper userMilkteaMapper;
    @Autowired
    private LotteryProperties lotteryProperties;

    /**
     * 查询抽奖奖池
     * @return
     */
    public List<Lottery> selectAll() {
        QueryWrapper<Lottery> qw = new QueryWrapper<>();
        qw.eq("status",1);
        return lotteryMapper.selectList(qw);
    }

    /**
     * 保存抽中的奖品
     * @param lottery
     */
    @Transactional
    public void lotteryRecord(Lottery lottery) {
        lottery = lotteryMapper.selectById(lottery.getId());

        User user = userMapper.selectById(BaseContext.getCurrentId());
        //判断抽中的奖品类型
        if (lottery.getType() == 1){
            String s = lottery.getName().split("积分")[0];
            user.setIntegral(user.getIntegral()+ Double.parseDouble(s));
            userMapper.updateById(user);
        }else if (lottery.getType() == 2 || lottery.getType() == 3){

            QueryWrapper<UserCoupon> qw = new QueryWrapper<>();
            qw.eq("coupon_id",lottery.getId());
            qw.eq("user_id",BaseContext.getCurrentId());
            UserCoupon userCoupon = userCouponMapper.selectOne(qw);

            if (userCoupon == null){
                Coupon coupon = couponMapper.selectById(lottery.getNameId());
                userCoupon = new UserCoupon();
                userCoupon.setUserId(BaseContext.getCurrentId());
                userCoupon.setCouponId(lottery.getNameId());
                userCoupon.setValidFrom(coupon.getCreatedAt());
                userCoupon.setValidUntil(coupon.getCreatedAt().plusDays(coupon.getValidTime()));
                userCouponMapper.updateById(userCoupon);
            }else {
                userCoupon.setNumber(userCoupon.getNumber()+1);
                userCouponMapper.updateById(userCoupon);
            }
        } else if (lottery.getType() == 4) {
            UserMilktea userMilktea = new UserMilktea();
            userMilktea.setUserId(BaseContext.getCurrentId());
            userMilktea.setMilkteaId(lottery.getNameId());
            userMilkteaMapper.insert(userMilktea);
        }
        UserLottery userLottery = new UserLottery();
        userLottery.setLotteryId(lottery.getId());
        userLottery.setTime(LocalDateTime.now());
        userLottery.setUserId(BaseContext.getCurrentId());
        userLotteryMapper.insert(userLottery);

        //减少积分
        user.setIntegral(user.getIntegral()-lotteryProperties.getIntegral());
        userMapper.updateById(user);
    }

    /**
     * 查询中奖记录
     * @return
     */
    public List<UserLotteryVO> selectRecord() {

        Long userId = BaseContext.getCurrentId();
        List<UserLotteryVO> list = new ArrayList<>();
        QueryWrapper<UserLottery> ulqw = new QueryWrapper<>();
        ulqw.eq("user_id",userId);
        List<UserLottery> userLotteries = userLotteryMapper.selectList(ulqw);
        for (UserLottery userLottery : userLotteries) {
            UserLotteryVO userLotteryVO = new UserLotteryVO();
            BeanUtils.copyProperties(userLottery,userLotteryVO);
            Lottery lottery = lotteryMapper.selectById(userLottery.getLotteryId());
            userLotteryVO.setName(lottery.getName());
            userLotteryVO.setUserId(lottery.getId());
            userLotteryVO.setImage(lottery.getImage());
            userLotteryVO.setType(lottery.getType());
            list.add(userLotteryVO);
        }
        return list;
    }

    /**
     * 管理端查询所有奖品信息
     * @return
     */
    public List<Lottery> selectAdminAll() {
        return lotteryMapper.selectList(new QueryWrapper<>());
    }

    /**
     * 更新抽奖信息
     * @param lottery
     */
    public void updateLottery(Lottery lottery) {
        Integer oldStatus = lottery.getStatus();
        lottery = lotteryMapper.selectById(lottery.getId());
        if (lottery.getType() == 2){
            Coupon coupon = couponMapper.selectById(lottery.getNameId());
            lottery.setName(coupon.getName());
            lottery.setImage(coupon.getImage());
        }

        if (lottery.getStatus() !=null && lottery.getStatus() == 0){

//            QueryWrapper<Lottery> qw = new QueryWrapper<>();
//            qw.eq("status",1);
//            Long l = lotteryMapper.selectCount(qw);
//            if (l<10) throw new BaseException("状态更新失败，奖池不能小于9个");
            lottery.setStatus(oldStatus);
            lotteryMapper.updateById(lottery);
        } else if (lottery.getStatus() !=null && lottery.getStatus() == 1) {
//            QueryWrapper<Lottery> qw = new QueryWrapper<>();
//            qw.eq("status",1);
//            Long l = lotteryMapper.selectCount(qw);
//            if (l>8) throw new BaseException("状态更新失败，奖池不能小于9个");
            lottery.setStatus(oldStatus);
            lotteryMapper.updateById(lottery);
        }else {
            lottery.setStatus(oldStatus);
            lotteryMapper.updateById(lottery);
        }
    }

    /**
     * 新增抽奖信息
     * @param lottery
     */
    public void insert(Lottery lottery) {
        if (lottery.getType() == 2){
            Coupon coupon = couponMapper.selectById(lottery.getNameId());
            lottery.setName(coupon.getName());
            lottery.setImage(coupon.getImage());
        }
        lottery.setStatus(0);
        lotteryMapper.insert(lottery);
    }

    /**
     * 删除抽奖信息
     * @param id
     */
    public void deleteById(Long id) {
        Lottery lottery = lotteryMapper.selectById(id);

        if (lottery.getStatus() == 1){
            throw new BaseException("启用的奖品禁止删除");
        }else{
            lotteryMapper.deleteById(id);
        }
    }

}
